#!/usr/bin/env python
import effess
import SCons.Variables
import SCons.Environment
import os.path as path
import sys
from SCons.Script import *
from subprocess import Popen

Import('build')

def package_app_builder(target, source, env):
	# Wait until the initial build is finished to do this import.
	import sdk.env

	pkg_env = sdk.env.PackagingEnvironment(build.os)
	app = pkg_env.create_app(env['PATH'])
	app.stage(path.join(build.dir, app.name), bundle=True, no_install=True, js_obfuscate=False)

	if ARGUMENTS.get('run', False):
		app.run()

def package_sdkinstaller(target, source, env):
	print "Packaging Titanium SDK Installer..."

	# Create a staged application, but don't bundle it, because we
	# want to force the installer to run and install the new SDK.
	import sdk.env
	pkg_env = sdk.env.PackagingEnvironment(build.os)
	app = pkg_env.create_app(env['PATH'])
	app.stage(path.join(build.dir, app.name), bundle=False, no_install=False, js_obfuscate=False)

	# Copy the zip files from the dist directory to developer.contents/dist
	print "    -> Copying sdk zip from %s to %s" % \
		(build.dist_dir, path.join(app.contents, 'dist'))
	effess.copy_to_dir(
		path.join(build.dist_dir, "sdk-" + build.version + ".zip"),
		path.join(app.contents, 'dist'))

	if ARGUMENTS.get('run', False):
		app.run()

build.env['BUILDERS']['PackageApp'] = build.env.Builder(
	action=package_app_builder,
	target_factory=SCons.Node.FS.default_fs.Entry,
	multi=0)
build.env['BUILDERS']['PackageSDKInstaller'] = build.env.Builder(
	action=package_sdkinstaller,
	target_factory=SCons.Node.FS.default_fs.Entry,
	multi=0)

def make_app_target(name, path):
	t = build.env.PackageApp('#titanium-app-' + name, [], PATH=path)
	Depends(t, build.build_targets + build.staging_targets)
	Alias(name, t)

make_app_target('developer', path.normpath("%s/../../titanium_developer" % build.cwd()))
make_app_target('testapp', path.join(build.cwd(), 'testapp'))
make_app_target('drillbit', path.join(build.cwd(), 'drillbit'))
make_app_target('sandbox', path.join(build.cwd(), 'sandbox'))

t = build.env.PackageSDKInstaller('#titanium-app-sdk-installer', [],
	PATH=path.join(build.cwd(), 'sdkinstaller'))
Depends(t, build.build_targets + build.staging_targets + build.dist_targets)
Alias('sdkinstaller', t)
